package com.atm.domain;

import java.util.Date;

import com.atm.physical.CardReader;
import com.atm.physical.CashDispenser;
import com.atm.physical.ReceiptPrinter;
import com.atm.simulation.bankSim.AccountServiceSim;

public class ATM {
	
	private Card card;
	private CardReader cardReader = new CardReader(); // 由ATM实例化读卡机
	private AccountServiceSim accountServiceSim = new AccountServiceSim();
	private Session session; 
	private Transaction transaction; 
	private CashDispenser cashDispenser = new CashDispenser(); // 提款机
	private ReceiptPrinter receiptPrinter = new ReceiptPrinter();
	private Receipt receipt;
	private Log log = new Log();

	public void turnOn() {
		System.out.println("ATM已启动");
		log.writeToFile("logs/log.log","开启一次服务"+"\n"); // 日志记录
		log.writeToFile("logs/log.log","ATM已经启动"+"\n");
		
	}

	public Card pluginCard(String cardNo) {
		card = cardReader.readCard(cardNo); // 由读卡机实例化卡
		log.writeToFile("logs/log.log","卡号：" + card.getCardNo()+"\n");
		return card;
	}

	public Session getSessionAfterIdentify(Card card, String password) {
		if (password!=null && accountServiceSim.verification(card.getCardNo(), password).isStatus()) {
			session = new Session(card, new Date()); // 远程银行系统实例化session
			log.writeToFile("logs/log.log","卡号：" + card.getCardNo() + "验证成功，创建session"+"\n");
		}
		return session;
	}

	public Transaction selectBusiness(int businessNo) {
		transaction = new Transaction(businessNo);
		log.writeToFile("logs/log.log","创建一次交易"+"\n");
		return transaction;
	}

	public boolean withdrawal(Card card, int amount) {
		if (accountServiceSim.withdrawal(card.getCardNo(), amount).isStatus()) {
			System.out.println("操作成功！");
			log.writeToFile("logs/log.log","卡号：" + card.getCardNo() + "取款成功"+"\n");
			return true;
		} else {
			System.out.println("操作失败！");
			log.writeToFile("logs/log.log","卡号：" + card.getCardNo() + "取款失败"+"\n");
			return false;
		}
	}

	public void getCash(int amount) {
		cashDispenser.spiltCash(amount);
		log.writeToFile("logs/log.log","出钞成功，可提取现金"+"\n");
		
	}

	public void printReceipt(Card card, int amount) {
		Date date = new Date();
		receipt = receiptPrinter.print(card, date, amount);

		System.out.println("时间：" + receipt.getDate());
		System.out.println("业务：" + receipt.getBusiness());
		System.out.println("卡号：" + receipt.getCard().getCardNo());
		System.out.println("取款金额：" + receipt.getAmount() + "元");
		
		log.writeToFile("logs/log.log","打印凭条成功"+"\n");
	}

	public void dropOut(Card card) {
		cardReader.ejectCard();
		log.writeToFile("logs/log.log","卡号：" + card.getCardNo() + "退卡成功"+"\n");
	}

	public void swallowCard(Card card) {
		cardReader.retainCard();
		log.writeToFile("logs/log.log","卡号：" + card.getCardNo() + "已锁定"+"\n");
	}

	public void turnOff() {
		System.out.println("ATM已关闭");
		log.writeToFile("logs/log.log","ATM已关闭"+"\n");
	}
}
